"""
应用启动脚本
"""
import sys
import os
import asyncio
import uvicorn
from pathlib import Path
from dotenv import load_dotenv

# 设置控制台编码为UTF-8，解决Windows中文乱码问题
if sys.platform == 'win32':
    try:
        # 设置标准输出编码为UTF-8
        if hasattr(sys.stdout, 'reconfigure'):
            sys.stdout.reconfigure(encoding='utf-8')
        if hasattr(sys.stderr, 'reconfigure'):
            sys.stderr.reconfigure(encoding='utf-8')
        # 设置环境变量
        os.environ['PYTHONIOENCODING'] = 'utf-8'
    except Exception:
        pass  # 如果设置失败，继续运行

# 手动加载 .env 文件
load_dotenv()

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from app.config import settings
from app.utils.logger import logger


def check_environment():
    """检查运行环境"""
    logger.info("检查运行环境...")
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        logger.error("Python版本必须 >= 3.8")
        sys.exit(1)
    
    logger.info(f"Python版本: {sys.version}")
    
    # 检查环境变量
    required_env_vars = [
        'WECHAT_APP_ID',
        'WECHAT_APP_SECRET', 
        'DEEPSEEK_API_KEY',
        'TONGYI_API_KEY',
        'DB_HOST',
        'DB_NAME',
        'DB_USER',
        'DB_PASSWORD'
    ]
    
    missing_vars = []
    for var in required_env_vars:
        if not os.getenv(var):
            missing_vars.append(var)
    
    if missing_vars:
        logger.error(f"缺少必要的环境变量: {', '.join(missing_vars)}")
        logger.info("请检查.env文件或设置相应的环境变量")
        sys.exit(1)
    
    logger.info("环境检查通过")


async def test_database_connection():
    """测试数据库连接"""
    try:
        from app.database import async_engine
        
        async with async_engine.begin() as conn:
            from sqlalchemy import text
            result = await conn.execute(text("SELECT 1"))
            result.fetchone()
        
        logger.info("数据库连接测试成功")
        return True
        
    except Exception as e:
        logger.error(f"数据库连接失败: {str(e)}")
        return False


def print_startup_info():
    """打印启动信息"""
    logger.info("=" * 60)
    logger.info("微信公众号文章自动生成工具")
    logger.info("=" * 60)
    logger.info(f"环境: {settings.environment}")
    logger.info(f"端口: {settings.app_port}")
    logger.info(f"数据库: {settings.db_host}:{settings.db_port}/{settings.db_name}")
    logger.info(f"微信AppID: {settings.wechat_app_id}")
    logger.info(f"DeepSeek API: {settings.deepseek_base_url}")
    logger.info(f"通义万相API: {settings.tongyi_base_url}")
    logger.info("=" * 60)


def main():
    """主函数"""
    try:
        print_startup_info()
        check_environment()
        
        # 测试数据库连接（开发模式下跳过）
        if settings.environment == "development":
            logger.warning("开发模式：跳过数据库连接预检")
        else:
            try:
                asyncio.run(test_database_connection())
            except Exception as e:
                logger.warning(f"数据库连接预检失败: {str(e)}")
                logger.info("应用将继续启动，数据库连接将在实际使用时重试")
        
        logger.info("启动FastAPI应用...")
        
        # 启动应用
        uvicorn.run(
            "app.main:app",
            host="0.0.0.0",
            port=settings.app_port,
            reload=settings.environment == "development",
            log_level="info",
            access_log=True,
            loop="asyncio",
            workers=1 if settings.environment == "development" else 4
        )
        
    except KeyboardInterrupt:
        logger.info("接收到中断信号，正在关闭应用...")
    except Exception as e:
        logger.error(f"应用启动失败: {str(e)}", exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    main()